import Request from '@/utils/request.js'
import { getToken, setToken, removeToken, saveUserInfo, loadUserinfo} from '@/utils/ProjectTools.js'
import {http} from "@/api";


// 重置用户令牌和角色信息
const state = {
    userInfo: loadUserinfo(),
    token: getToken(),
    valid: false, // 当前路由是否有效
    roles: {}, //角色信息
    menuList: [],
    dictList: [],
    dictMap: {},
}



const mutations = {
    SET_USERINFO: (state, data) => {
        saveUserInfo(data)
        state.userInfo = data
    },
    SET_TOKEN: (state, token) => {
        setToken(token)
        state.token = token
    },
    LOGOUT(state) {
        removeToken();
        state.userInfo = {};
        state.token = '';
        state.valid = false;
        state.roles = null;
    },
    SET_MENUS: (state, data) => {
        state.menuList = data;
    },
    USER_ROLES: (state, data) => {
        state.roles = data;
    },
    SET_VALID: (state) => {
        state.valid = true;
    },
    SET_DICT: (state, data) => {
        state.dictList = data;
        const dictDataMap = new Map()
        data.forEach((dictData) => {
            // 获得 dictType 层级
            const enumValueObj = dictDataMap[dictData.dictType]
            if (!enumValueObj) {
                dictDataMap[dictData.dictType] = []
            }
            // 处理 dictValue 层级
            dictDataMap[dictData.dictType].push({
                value: dictData.value,
                label: dictData.label,
                colorType: dictData.colorType,
                cssClass: dictData.cssClass
            })
        })
        state.dictMap = dictDataMap
    },
};

const actions = {
    // 获取验证码
    getLoginCaptcha() {
        return Request.get("/public/admin/captcha")
            .then(res => {
                return Promise.resolve(res.data);
            })
            .catch(err => {
                return Promise.reject(err);
            });

    },
    // 用户登录
    login({ commit, dispatch }, userInfo) {
        const { username, password } = userInfo
        return new Promise(async (resolve, reject) => {
            http.login({ username, password }).then(res => {
                commit('SET_TOKEN', res.data);
                resolve()
            }).catch(() => {
                reject()
            })
        })
    },
    // 重置令牌
    resetToken({ commit,dispatch }) {
        return new Promise((resolve, reject) => {
            dispatch('tagsView/delAllViews',null,{ root: true })
            Request({
                url: '/public/admin/login/out',
                method: 'get',
            }).then(()=>{
                commit('LOGOUT')
                resolve()
            }).catch(()=>{
                commit('LOGOUT')
                resolve()
            })
        })
    },
    // 当前路由是否有效
    setValid({ commit }) {
        commit('SET_VALID')
    },
    // 获取用户角色
    getUserRoles({ commit }, id) {
        return new Promise((resolve, reject) => {
            http.getUserInfo().then(res => {
                if (res.data.menus.length === 0) {
                    reject('无权限')
                }
                commit("USER_ROLES", res.data);
                commit("SET_USERINFO", res.data.user);
                commit("SET_MENUS", res.data.menus);
                resolve(res.data)
            }).catch(() => {
                reject()
            })
        })
    },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
